package com.zbkj.admin.config;

import com.alibaba.fastjson.JSONObject;
import com.zbkj.admin.result.CommonResult;
import com.zbkj.admin.result.CommonResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.constant.MicaConstant;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.WebUtil;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 成功、失败的处理器
 *
 * @author L.cm
 */
@Slf4j
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
public class SecAuthHandler extends AccessDeniedHandlerImpl implements AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler {
    private final ApplicationEventPublisher publisher;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) {
        if (response.isCommitted()) {
            return;
        }
        // 没有权限 403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        WebUtil.renderJson(response, R.fail("没有权限访问"));
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) {
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        try {
            response.getWriter().print(JSONObject.toJSONString(CommonResult.failed(CommonResultCode.UNAUTHORIZED)));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {

    }

    /**
     * 获取请求时间
     *
     * @param request HttpServletRequest
     * @return 请求时间
     */
    private static long getRequestTime(HttpServletRequest request) {
        Long requestStartTime = (Long) request.getAttribute(MicaConstant.REQUEST_START_TIME);
        if (requestStartTime == null) {
            return 0L;
        }
        return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - requestStartTime);
    }
}
